package cn.com.haopy.yue.ai.admin.web;

import cn.com.haopy.yue.ai.admin.annotation.RequiresPermissionsDesc;
import cn.com.haopy.yue.ai.admin.vo.IndexVo;
import cn.com.haopy.yue.ai.admin.vo.TopicVo;
import cn.com.haopy.yue.ai.core.utils.JacksonUtil;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.core.validator.Order;
import cn.com.haopy.yue.ai.core.validator.Sort;
import cn.com.haopy.yue.ai.db.entity.arisk.*;
import cn.com.haopy.yue.ai.db.service.hos.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Description: TODO
 * @Author DuTao
 * @Date 2025/3/28 8:57
 */
@RestController
@RequestMapping("/admin/risk/illness")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "评估疾病相关")
public class AdminAIRiskIllnessController {
    @Autowired
    private AIRiskIllnessService riskIllnessService;

    @Autowired
    private AIRiskIllnessCheckIndexService riskIllnessCheckIndexService;

    @Autowired
    private AIRiskCheckIndexService riskCheckIndexService;

    @Autowired
    private AIRiskIllnessTopicService riskIllnessTopicService;

    @Autowired
    private AIRiskTopicService riskTopicService;

    @Autowired
    private AIRiskIllnessDrugsService riskIllnessDrugsService;

    @RequiresPermissions("admin:risk:illness:list")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "列表查询")
    @GetMapping("/list")
    @ApiOperation("列表")
    public Object list(@RequestParam(required = false) @ApiParam("疾病名称") String name,
                       @RequestParam(required = false) @ApiParam("提问内容") String question,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "create_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        Page<AIRiskIllness> riskIllnessList = riskIllnessService.querySelective(name, question, page, limit, sort, order);
        return ResponseUtil.okPage(riskIllnessList);
    }

    @RequiresPermissions("admin:risk:illness:create")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "新增")
    @PostMapping("/create")
    @ApiOperation("新增")
    @Transactional
    public Object create(@RequestBody AIRiskIllness riskIllness) {
        Object error = validate(riskIllness);
        if (error != null) {
            return error;
        }
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        riskIllness.setCreateBy(admin.getUsername());
        riskIllness.setUpdateBy(admin.getUsername());
        // todo 是否需要进行唯一性校验
//        List<AIRiskCheckIndexResult> checkIndexResultList = checkIndexResultService.getByName(checkIndexResult.getCheckIndexName());
//        if (!CollectionUtils.isEmpty(checkIndexResultList)) {
//            return ResponseUtil.fail("指标已经存在");
//        }
        boolean isSuccess = riskIllnessService.save(riskIllness);
        if (!isSuccess) {
            return ResponseUtil.fail("添加失败");
        }
        return ResponseUtil.ok("添加成功");
    }

    @RequiresPermissions("admin:risk:illness:update")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "修改")
    @PostMapping("/update")
    @ApiOperation("编辑")
    @Transactional
    public Object update(@RequestBody AIRiskIllness riskIllness) {
        AIRiskIllness riskIllnessEntity = riskIllnessService.getById(riskIllness.getId());
        if (Objects.isNull(riskIllnessEntity)) {
            return ResponseUtil.fail("信息不存在");
        }

        // todo 指标唯一性校验
//        if (!Objects.equals(riskIllness.getCheckIndexName(), checkIndexResultEntity.getCheckIndexName())) {
//            List<AIRiskCheckIndexResult> checkIndexResultList = checkIndexResultService.getByName(riskIllness.getCheckIndexName());
//            if (!CollectionUtils.isEmpty(checkIndexResultList)) {
//                return ResponseUtil.fail("指标已经存在！");
//            }
//        }
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        riskIllness.setUpdateBy(admin.getUsername());
        if (riskIllnessService.updateById(riskIllness)) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @RequiresPermissions("admin:risk:illness:topic:assigned")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "问题分配")
    @PostMapping("/topic/assigned")
    @ApiOperation("问题分配")
    @Transactional
    public Object topicAssigned(@RequestBody String body) {
        Integer illnessId = JacksonUtil.parseInteger(body, "illnessId");
        List<Integer> topicList = JacksonUtil.parseIntegerList(body, "topicList");

        // 校验疾病是否存在
        AIRiskIllness entity = riskIllnessService.getById(illnessId);
        if (Objects.isNull(entity)) {
            return ResponseUtil.fail("疾病信息不存在");
        }
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        if (!CollectionUtils.isEmpty(topicList)) {
            List<AIRiskIllnessTopic> allTopicList = riskIllnessTopicService.getAll(illnessId);
            List<AIRiskIllnessTopic> deleteAll = riskIllnessTopicService.getDeleteAll(illnessId);
            allTopicList.addAll(deleteAll);
            if (CollectionUtils.isEmpty(allTopicList)) {
                for (Integer topicId : topicList) {
                    AIRiskIllnessTopic riskIllnessTopic = new AIRiskIllnessTopic();
                    riskIllnessTopic.setIllnessId(illnessId);
                    riskIllnessTopic.setTopicId(topicId);
                    riskIllnessTopic.setCreateBy(admin.getUsername());
                    riskIllnessTopic.setUpdateBy(admin.getUsername());
                    riskIllnessTopicService.save(riskIllnessTopic);
                }
            } else {
                if (allTopicList.size() > topicList.size()) {
                    for (AIRiskIllnessTopic riskIllnessTopic : allTopicList) {
                        if (!topicList.contains(riskIllnessTopic.getTopicId())) {
                            riskIllnessTopicService.removeById(riskIllnessTopic.getId());
                        }
                    }
                }
                // 接口性能问题 多线程执行，快1s左右
//                topicList.forEach(topicId -> {
//                    ExecutorCore.execute(() -> {
//                        AIRiskIllnessTopic checkIndexEntity = riskIllnessTopicService.getByCondition(illnessId, topicId);
//                        AIRiskIllnessTopic checkIndexEntity1 = riskIllnessTopicService.getByIllnessIdAndIndexId(illnessId, topicId);
//                        if (Objects.isNull(checkIndexEntity) && Objects.isNull(checkIndexEntity1)) {
//                            // 指标不存在关系（包括有效关系/无效关系），代表关系是第一次添加
//                            AIRiskIllnessTopic entity1 = new AIRiskIllnessTopic();
//                            entity1.setUpdateBy(admin.getUsername());
//                            entity1.setCreateBy(admin.getUsername());
//                            entity1.setIllnessId(illnessId);
//                            entity1.setTopicId(topicId);
//                            riskIllnessTopicService.save(entity1);
//                        }
//                        if (Objects.nonNull(checkIndexEntity1)) {
//                            checkIndexEntity1.setDeleted(false);
//                            checkIndexEntity1.setUpdateBy(admin.getUsername());
//                            riskIllnessTopicService.updateDelete(checkIndexEntity1);
//                        }
//                    });
//                });

                for (Integer topicId : topicList) {
                    AIRiskIllnessTopic checkIndexEntity = riskIllnessTopicService.getByCondition(illnessId, topicId);
                    AIRiskIllnessTopic checkIndexEntity1 = riskIllnessTopicService.getByIllnessIdAndIndexId(illnessId, topicId);
                    if (Objects.isNull(checkIndexEntity) && Objects.isNull(checkIndexEntity1)) {
                        // 指标不存在关系（包括有效关系/无效关系），代表关系是第一次添加
                        AIRiskIllnessTopic entity1 = new AIRiskIllnessTopic();
                        entity1.setUpdateBy(admin.getUsername());
                        entity1.setCreateBy(admin.getUsername());
                        entity1.setIllnessId(illnessId);
                        entity1.setTopicId(topicId);
                        riskIllnessTopicService.save(entity1);
                    }
                    // 当前指标存在关系（包括有效关系/无效关系），有效关系不用处理，无效关系恢复关系
                    if (Objects.nonNull(checkIndexEntity)) {
                        continue;
                    }
                    if (Objects.nonNull(checkIndexEntity1)) {
                        checkIndexEntity1.setDeleted(false);
                        checkIndexEntity1.setUpdateBy(admin.getUsername());
                        riskIllnessTopicService.updateDelete(checkIndexEntity1);
                    }
                }
            }
        }
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:risk:illness:topic:get")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "问题详情")
    @GetMapping("/topic/get")
    @ApiOperation("问题详情")
    public Object getIllnessTopics(Integer illnessId) {
        List<TopicVo> allTopicList = getAllTopicList();
        Set<Integer> assignedTopicList = getAssignedTopicList(illnessId);

        Map<String, Object> data = new HashMap<>();
        data.put("assignedTopicList", assignedTopicList);
        data.put("allTopicList", allTopicList);
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:risk:illness:index:assigned")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "指标分配")
    @PostMapping("/index/assigned")
    @ApiOperation("指标分配")
    @Transactional
    public Object indexAssigned(@RequestBody String body) {
        Integer illnessId = JacksonUtil.parseInteger(body, "illnessId");
        List<Integer> indexList = JacksonUtil.parseIntegerList(body, "indexList");

        // 校验疾病是否存在
        AIRiskIllness entity = riskIllnessService.getById(illnessId);
        if (Objects.isNull(entity)) {
            return ResponseUtil.fail("疾病信息不存在");
        }
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        if (!CollectionUtils.isEmpty(indexList)) {
            List<AIRiskIllnessCheckIndex> allIndexList = riskIllnessCheckIndexService.getAll(illnessId);
            List<AIRiskIllnessCheckIndex> deleteAll = riskIllnessCheckIndexService.getDeleteAll(illnessId);
            allIndexList.addAll(deleteAll);
            if (CollectionUtils.isEmpty(allIndexList)) {
                for (Integer indexId : indexList) {
                    AIRiskIllnessCheckIndex riskIllnessCheckIndex = new AIRiskIllnessCheckIndex();
                    riskIllnessCheckIndex.setIllnessId(illnessId);
                    riskIllnessCheckIndex.setIndexId(indexId);
                    riskIllnessCheckIndex.setCreateBy(admin.getUsername());
                    riskIllnessCheckIndex.setUpdateBy(admin.getUsername());
                    riskIllnessCheckIndexService.save(riskIllnessCheckIndex);
                }
            } else {
                if (allIndexList.size() > indexList.size()) {
                    for (AIRiskIllnessCheckIndex aiRiskIllnessCheckIndex : allIndexList) {
                        if (!indexList.contains(aiRiskIllnessCheckIndex.getIndexId())) {
                            riskIllnessCheckIndexService.removeById(aiRiskIllnessCheckIndex.getId());
                        }
                    }
                }
                for (Integer indexId : indexList) {
                    AIRiskIllnessCheckIndex checkIndexEntity1 = riskIllnessCheckIndexService.getByCondition(illnessId, indexId);
                    AIRiskIllnessCheckIndex checkIndexEntity2 = riskIllnessCheckIndexService.getByIllnessIdAndIndexId(illnessId, indexId);
                    if (Objects.isNull(checkIndexEntity1) && Objects.isNull(checkIndexEntity2)) {
                        // 指标不存在关系（包括有效关系/无效关系），代表关系是第一次添加
                        AIRiskIllnessCheckIndex entity1 = new AIRiskIllnessCheckIndex();
                        entity1.setUpdateBy(admin.getUsername());
                        entity1.setCreateBy(admin.getUsername());
                        entity1.setIllnessId(illnessId);
                        entity1.setIndexId(indexId);
                        riskIllnessCheckIndexService.save(entity1);
                    }
                    // 当前指标存在关系（包括有效关系/无效关系），有效关系不用处理，无效关系恢复关系
                    if (Objects.nonNull(checkIndexEntity1)) {
                        continue;
                    }
                    if (Objects.nonNull(checkIndexEntity2)) {
                        checkIndexEntity2.setDeleted(false);
                        checkIndexEntity2.setUpdateBy(admin.getUsername());
                        riskIllnessCheckIndexService.updateDelete(checkIndexEntity2);
                    }
                }
            }
        }
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:risk:illness:index:get")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "指标详情")
    @GetMapping("/index/get")
    @ApiOperation("指标详情")
    public Object getIllnessIndex(Integer illnessId) {
        List<IndexVo> allIndexList = getAllIndexList();
        Set<Integer> assignedIndexList = getAssignedIndexList(illnessId);

        Map<String, Object> data = new HashMap<>();
        data.put("assignedIndexList", assignedIndexList);
        data.put("allIndexList", allIndexList);
        return ResponseUtil.ok(data);
    }

    private Set<Integer> getAssignedIndexList(Integer illnessId) {
        Set<Integer> assignedIndexes = new HashSet<>();
        List<AIRiskIllnessCheckIndex> resultList = riskIllnessCheckIndexService.getByIllnessId(illnessId);
        if (!CollectionUtils.isEmpty(resultList)) {
            for (AIRiskIllnessCheckIndex entity : resultList) {
                assignedIndexes.add(entity.getIndexId());
            }
        }
        return assignedIndexes;
    }

    private Set<Integer> getAssignedTopicList(Integer illnessId) {
        Set<Integer> assignedTopics = new HashSet<>();
        List<AIRiskIllnessTopic> resultList = riskIllnessTopicService.getByIllnessId(illnessId);
        if (!CollectionUtils.isEmpty(resultList)) {
            for (AIRiskIllnessTopic entity : resultList) {
                assignedTopics.add(entity.getTopicId());
            }
        }
        return assignedTopics;
    }

    /**
     * 获取所有指标项
     *
     * @return
     */
    private List<IndexVo> getAllIndexList() {
        List<IndexVo> indexVoList = new ArrayList<>();
        List<AIRiskCheckIndex> itemList = riskCheckIndexService.list();
        if (!CollectionUtils.isEmpty(itemList)) {
            for (AIRiskCheckIndex entity : itemList) {
                IndexVo indexVo = new IndexVo();
                indexVo.setIndexId(entity.getId());
                indexVo.setIndexName(entity.getCheckIndexName());
                indexVoList.add(indexVo);
            }
        }
        return indexVoList;
    }

    private List<TopicVo> getAllTopicList() {
        List<TopicVo> topicVoList = new ArrayList<>();
        List<AIRiskTopic> itemList = riskTopicService.list();
        if (!CollectionUtils.isEmpty(itemList)) {
            for (AIRiskTopic entity : itemList) {
                TopicVo topicVo = new TopicVo();
                topicVo.setTopicId(entity.getId());
                topicVo.setTopicName(entity.getTopic());
                topicVoList.add(topicVo);
            }
        }
        return topicVoList;
    }

    @RequiresPermissions("admin:risk:illness:detail")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "详情")
    @GetMapping("/detail")
    @ApiOperation("详情")
    @Transactional
    public Object detail(@RequestParam Integer id) {
        AIRiskIllness entity = riskIllnessService.getById(id);
        if (Objects.nonNull(entity)) {
            return ResponseUtil.ok(entity);
        } else {
            return ResponseUtil.fail("获取数据失败");
        }
    }

    @RequiresPermissions("admin:risk:illness:delete")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "删除")
    @GetMapping("/delete")
    @ApiOperation("删除")
    @Transactional
    public Object delete(@RequestParam Integer id) {
        if (riskIllnessService.removeById(id)) {
            return ResponseUtil.ok("删除成功");
        }
        return ResponseUtil.fail("删除数据失败");
    }

    private Object validate(AIRiskIllness data) {
        if (!StringUtils.hasText(data.getName())) {
            return ResponseUtil.badArgumentValue();
        }
        if (!StringUtils.hasText(data.getQuestion())) {
            return ResponseUtil.badArgumentValue();
        }
        return null;
    }

    @RequiresPermissions("admin:risk:illness:drug:assigned")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "药品分配列表")
    @GetMapping("/drug/assigned")
    @ApiOperation("药品分配列表")
    public Object drugAssigned(@RequestParam(required = false) @ApiParam("药品名称") String drugName,
                               @RequestParam @ApiParam("疾病id") Integer illnessId,
                               @RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize) {
        IPage<AIRiskIllnessDrugs> aiRiskIllnessDrugsIPage = riskIllnessDrugsService.querySelective(drugName, illnessId, pageNum, pageSize);
        return ResponseUtil.ok(aiRiskIllnessDrugsIPage);
      }

    @RequiresPermissions("admin:risk:illness:drug:add")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "新增疾病药品")
    @PostMapping("/drug/add")
    @ApiOperation("新增疾病药品")
    @Transactional
    public Object addDrug(@RequestBody AIRiskIllnessDrugs riskIllnessDrug) {
        if (Objects.isNull(riskIllnessDrug.getDrugName())) {
            return ResponseUtil.fail("药品名称不能为空");
        }
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        riskIllnessDrug.setCreateBy(admin.getUsername());
        riskIllnessDrug.setUpdateBy(admin.getUsername());
        List<AIRiskIllnessDrugs> riskIllnessDrugList = riskIllnessDrugsService.getByName(riskIllnessDrug.getIllnessId(), riskIllnessDrug.getDrugName());
        if (!CollectionUtils.isEmpty(riskIllnessDrugList)) {
            return ResponseUtil.fail("疾病药品已经存在");
        }
        boolean isSuccess = riskIllnessDrugsService.save(riskIllnessDrug);
        if (!isSuccess) {
            return ResponseUtil.fail("添加失败");
        }
        return ResponseUtil.ok("添加成功");
    }

    @RequiresPermissions("admin:risk:illness:drug:edit")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "编辑疾病药品")
    @PostMapping("/drug/edit")
    @ApiOperation("编辑疾病药品")
    @Transactional
    public Object updateDrug(@RequestBody AIRiskIllnessDrugs riskIllnessDrug) {
        AIRiskIllnessDrugs illnessDrug = riskIllnessDrugsService.getById(riskIllnessDrug);
        if (Objects.isNull(illnessDrug)) {
            return ResponseUtil.fail("疾病药品数据不存在");
        }
        if (!Objects.equals(riskIllnessDrug.getDrugName(), illnessDrug.getDrugName())) {
            List<AIRiskIllnessDrugs> illnessDrugs = riskIllnessDrugsService.getByName(riskIllnessDrug.getIllnessId(), riskIllnessDrug.getDrugName());
            if (!CollectionUtils.isEmpty(illnessDrugs)) {
                return ResponseUtil.fail("该疾病药品已经存在");
            }
        }
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        riskIllnessDrug.setUpdateBy(admin.getUsername());
        if (riskIllnessDrugsService.updateById(riskIllnessDrug)) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @RequiresPermissions("admin:risk:illness:drug:delete")
    @RequiresPermissionsDesc(menu = {"信息维护", "评估疾病管理"}, button = "删除疾病药品")
    @GetMapping("/drug/delete")
    @ApiOperation("删除疾病药品")
    @Transactional
    public Object remove(Integer id) {
        return ResponseUtil.ok(riskIllnessDrugsService.removeById(id));
    }
}
